package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    BCryptPasswordEncoder passwordConfig;

    /**
     * 校验数据是否可用
     *
     * @param date 数据
     * @param type 类型
     * @return
     */
    public Boolean checkDate(String date, Integer type) {
        User user = new User();
        if (type == 1) {
            user.setUsername(date);
        } else if (type == 2) {
            user.setPhone(date);

        } else {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);

        }
        User user1 = userMapper.selectOne(user);
        return user1 == null;

    }

    /**
     * 发送验证码短信
     *
     * @param phone
     */
    public void sendCode(String phone) {
//校验手机号码格式
        if (!RegexUtils.isPhone(phone)) {

            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //生成短信验证码
        String code = RandomStringUtils.randomNumeric(6);
        //保存验证码到redis
        redisTemplate.opsForValue().set("user:code:phone:" + phone, code, 5, TimeUnit.MINUTES);
        //发送rabbitMQ信息到ly-sms
        HashMap<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        //    amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,MQConstants.RoutingKey.VERIFY_CODE_KEY,msg);

    }

    /**
     * 注册用户
     *
     * @param user
     * @param code
     */
    public void registerUser(User user, String code) {
        // 1 校验验证码
        // 1.1 取出redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get("user:code:phone:" + user.getPhone());
        // 1.2 比较验证码
        if (!StringUtils.equals(code, cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        // 2 对密码加密
        user.setPassword(passwordConfig.encode(user.getPassword()));
        // 3 写入数据库
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    /**
     * 根据用户名密码查询用户
     * @param
     * @param username
     * @param password
     * @return
     */
    public UserDTO queryUser(String username, String password) {
        User user1 = new User();
        user1.setUsername(username);
        User user2 = userMapper.selectOne(user1);
        if (user2 == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        if (!passwordConfig.matches(password, user2.getPassword())) {
            // 密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);

        }
        return BeanHelper.copyProperties(user2, UserDTO.class);
    }
}